package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.commom.exception.CustException;
import com.heima.model.admin.dtos.UserDTO;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by jojo
 * @Date 2022/2/26
 * @Description
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(UserDTO dto) {
        //1.校验参数
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }
        //2.根据用户名查询用户信息
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName,dto.getName());
        //执行查询代码
        AdUser user = this.getOne(wrapper);
        //判断用户名是否正确
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"输入用户名错误");
        }
        //判断状态码是否可用
        if (user.getStatus().intValue() !=9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"状态码异常");
        }
        //3 获取数据库密码和盐， 匹配密码
        String dbPswd = user.getPassword();
        String salt = user.getSalt();
        String loginPswd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!dbPswd.equals(loginPswd)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"输入密码错误");
        }
        //4.修改登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //5.颁发token jwt 令牌
        String token = AppJwtUtil.getToken(user.getId().longValue());
        //返回用户信息 Vo
        AdUserVO vo = new AdUserVO();
        BeanUtils.copyProperties(user,vo);
        //响应数据
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",vo);
        return ResponseResult.okResult(map);
    }
}
